﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.Persistent.Base;

namespace EasyXaf.ExcelImporters;

public class ImportExcelController : ViewController<ListView>
{
    public SingleChoiceAction ImportAction { get; }

    public ImportExcelController()
    {
        ImportAction = new SingleChoiceAction(this, "ImportExcelAction", PredefinedCategory.Export)
        {
            Caption = "Import Excel",
            ImageName = "Import",
            ShowItemsOnClick = true,
            ItemType = SingleChoiceActionItemType.ItemIsOperation
        };
    }

    protected override void OnActivated()
    {
        base.OnActivated();

        if (Application.Model is IModelApplicationImportings model)
        {
            var importingModels = model.Importings
                .Where(x => x.Enable)
                .Where(x => x.ModelClass == View.Model.ModelClass)
                .OrderBy(x => x.Index)
                .ToList();

            if (importingModels.Any())
            {
                ImportAction.Active.RemoveItem("Disable this action when ImportingModel is null");
                ImportAction.Items.Clear();

                foreach (var importingModel in importingModels)
                {
                    var importExcelAction = new ChoiceActionItem("ImportExcel", "导入Excel", importingModel);
                    var excelTemplateAction = new ChoiceActionItem("ExcelTemplate", "Excel模板", importingModel);

                    if (importingModels.Count > 1)
                    {
                        var importingModelMenu = new ChoiceActionItem(importingModel.GetCaption(), null);
                        importingModelMenu.Items.Add(importExcelAction);
                        importingModelMenu.Items.Add(excelTemplateAction);
                        ImportAction.Items.Add(importingModelMenu);
                    }
                    else
                    {
                        ImportAction.Items.Add(importExcelAction);
                        ImportAction.Items.Add(excelTemplateAction);
                    }
                }
            }
            else
            {
                ImportAction.Active["Disable this action when ImportingModel is null"] = false;
            }
        }
    }
}
